package com.cande.loki.exercise.bytebuddy;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import static net.bytebuddy.matcher.ElementMatchers.*;

/**
 * @Description TODO
 * @Author wgf
 * @Date 2025/3/21 4:20 PM
 */
public class Test {
    public static void main(String[] args) {
        test4();

    }

    public static void test4() {
        try {
            DynamicType.Unloaded<Target> agent = new ByteBuddy()
                    .subclass(Target.class)
                    .method(named("saySomething")
                            .and(isDeclaredBy(Target.class)
                                    .and(returns(String.class))))
                    .intercept(MethodDelegation.to(Agent.class))
                    .make();

          String aa= agent.load(ClassLoader.getSystemClassLoader())
                    .getLoaded().newInstance().saySomething();
            System.out.println(aa);
            // 将 agent 字节码写入文件中
            outputClazz(agent.getBytes());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static void outputClazz(byte[] bytes) {
        FileOutputStream out = null;
        try {
            String pathName = Test.class.getResource("/").getPath() + "AgentTarget.class";
            out = new FileOutputStream(new File(pathName));
            System.out.println("类输出路径：" + pathName);
            out.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

